﻿namespace SFWS.XJSON.Core
{
    using SFWS.XJSON.Core.Properties;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;

    public sealed class JsonObject
    {
        internal Dictionary<string, object> Pairs = new Dictionary<string, object>();

        public JsonObject Add(JsonObject jo)
        {
            if (jo != null)
            {
                foreach (KeyValuePair<string, object> pair in jo.Pairs)
                {
                    this.Pairs.Add(pair.Key, pair.Value);
                }
            }
            return this;
        }

        public JsonObject Add(string key, object val)
        {
            if (string.IsNullOrEmpty(key))
            {
                throw new ApplicationException(Resources.JsonObjectKeyException);
            }
            if (this.Pairs.ContainsKey(key))
            {
                this.Pairs[key] = val;
            }
            else
            {
                this.Pairs.Add(key, val);
            }
            return this;
        }

        public void Clear()
        {
            this.Pairs.Clear();
        }

        public bool ContainsKey(string key)
        {
            return this.Pairs.ContainsKey(key);
        }

        public static JsonObject Create(params object[] kv)
        {
            if ((kv.Length % 2) != 0)
            {
                throw new ApplicationException(Resources.JsonObjectParaCountException);
            }
            JsonObject obj2 = new JsonObject();
            for (int i = 0; i < kv.Length; i += 2)
            {
                object obj3 = kv[i];
                if (((obj3 == null) || !(obj3 is string)) || (obj3.ToString() == ""))
                {
                    throw new ApplicationException(Resources.JsonObjectKeyException);
                }
                obj2.Add(obj3.ToString(), kv[i + 1]);
            }
            return obj2;
        }

        public JsonObject Remove(string key)
        {
            this.Pairs.Remove(key);
            return this;
        }

        [JsonIgnore]
        public int Count
        {
            get
            {
                return this.Pairs.Count;
            }
        }

        public object this[string key]
        {
            get
            {
                return (this.Pairs.ContainsKey(key) ? this.Pairs[key] : null);
            }
        }

        [JsonIgnore]
        public List<string> Keys
        {
            get
            {
                return this.Pairs.Keys.ToList<string>();
            }
        }
    }
}

